#include "types.h"
#include "stat.h"
#include "user.h"
#include "fcntl.h"

int main(int argc, char *argv[])
{
  if(argc < 3)
    {
	printf(1,"not enough params\n");
	exit();
    }
  if((fprot(argv[1],argv[2]))<0)
     {
	printf(1,"failed to protect file\n");
	exit();
     }
  int pid = fork();
	if(pid!=0)
	{
	wait();
	printf(1,"opening locked file\n");
	  int fd = open(argv[1],O_RDWR);
	  if(fd<0)
		{
        	printf(1,"file open failed:%d\n",fd);
		if((funprot(argv[1],argv[2]))<0)
		     {
			printf(1,"failed to unprotect file\n");
			exit();
		     }
		}		
	   else
		{
		printf(1,"unprotected file\n");
		close(fd);
		exit();
		}
	}
	else
	{
	printf(1,"unlocking file\n");
	   if((funlock(argv[1],argv[2]))<0)
	     	{
		printf(1,"failed to unlock file\n");
		exit();
		}
	  printf(1,"opening unlocked file\n");
	  int fd = open(argv[1],O_RDWR);
	  if(fd<0)
	    {
	        printf(1,"child file open failed:%d\n",fd);
	        exit();
	    }
	char buf[512];
	int n;
  	while((n = read(fd, buf, sizeof(buf))) > 0)
    		write(1, buf, n);
	close(fd);
	exit();
	}

exit();
}
